package com.ruoyi.training.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.examination.domain.PaperConfig;
import com.ruoyi.examination.mapper.PaperConfigMapper;
import com.ruoyi.examination.service.IPaperConfigService;
import com.ruoyi.system.api.RemoteDeptService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.training.domain.ExamSchedule;
import com.ruoyi.training.domain.Projects;
import com.ruoyi.training.domain.Remarks;
import com.ruoyi.training.dto.PeopleAllocationDTO;
import com.ruoyi.training.dto.PeopleItemDTO;
import com.ruoyi.training.dto.TrainingClassDto;
import com.ruoyi.training.mapper.ClassStudentMapper;
import com.ruoyi.training.mapper.ExamScheduleMapper;
import com.ruoyi.training.mapper.SatisfactionSurveyMapper;
import com.ruoyi.training.service.IProjectsService;
import com.ruoyi.training.service.IRemarksService;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import com.ruoyi.training.vo.TrainClassVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.training.mapper.TrainingClassMapper;
import com.ruoyi.training.domain.TrainingClass;
import com.ruoyi.training.service.ITrainingClassService;

/**
 * 培训班主Service业务层处理
 *
 * @author WorrilessGo
 * @date 2025-09-24
 */
@Service
public class TrainingClassServiceImpl implements ITrainingClassService {
    private static final SnowflakeIdUtils snowflake = new SnowflakeIdUtils(5, 8);

    @Autowired
    private TrainingClassMapper trainingClassMapper;

    @Autowired
    private IProjectsService projectsService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private RemoteDeptService remoteDeptService;

    @Autowired
    private IRemarksService iRemarksService;

    @Autowired
    private ExamScheduleMapper examScheduleMapper;

    @Autowired
    private PaperConfigMapper paperConfigMapper;

    @Autowired
    private ClassStudentMapper classStudentMapper;

    @Autowired
    private SatisfactionSurveyMapper satisfactionSurveyMapper;


    /**
     * 查询培训班主
     *
     * @param trainingClassId 培训班主主键
     * @return 培训班主
     */
    @Override
    public TrainingClass selectTrainingClassByTrainingClassId(String trainingClassId) {
        return trainingClassMapper.selectTrainingClassByTrainingClassId(trainingClassId);
    }

    /**
     * 查询培训班主列表
     *
     * @param trainingClass 培训班主
     * @return 培训班主
     */
    @Override
    public List<TrainingClass> selectTrainingClassList(TrainingClass trainingClass) {
        return trainingClassMapper.selectTrainingClassList(trainingClass);
    }

    /**
     * 新增培训班主
     *
     * @param trainingClass 培训班主
     * @return 结果
     */
    @Override
    public int insertTrainingClass(TrainingClass trainingClass) {
        trainingClass.setTrainingClassId(String.valueOf(new SnowflakeIdUtils(5, 8).nextId()));
        trainingClass.setCreateTime(DateUtils.getNowDate());
        trainingClass.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        trainingClass.setIsRemove("0");
        return trainingClassMapper.insertTrainingClass(trainingClass);
    }

    /**
     * 修改培训班主
     *
     * @param trainingClass 培训班主
     * @return 结果
     */
    @Override
    public int updateTrainingClass(TrainingClass trainingClass) {
        trainingClass.setUpdateTime(DateUtils.getNowDate());
        trainingClass.setUpdateBy(SecurityUtils.getUsername());
        return trainingClassMapper.updateTrainingClass(trainingClass);
    }

    /**
     * 批量删除培训班主
     *
     * @param trainingClassIds 需要删除的培训班主主键
     * @return 结果
     */
    @Override
    public int deleteTrainingClassByTrainingClassIds(String[] trainingClassIds) {
//        return trainingClassMapper.deleteTrainingClassByTrainingClassIds(trainingClassIds);
        //逻辑删除
        return trainingClassMapper.updateTrainingClassIsRemoveByTrainingClassIds(trainingClassIds);
    }

    /**
     * 删除培训班主信息
     *
     * @param trainingClassId 培训班主主键
     * @return 结果
     */
    @Override
    public int deleteTrainingClassByTrainingClassId(String trainingClassId) {
        return trainingClassMapper.deleteTrainingClassByTrainingClassId(trainingClassId);
    }

    /**
     * 通过项目和条件查询培训班主列表
     * lqx
     */
    @Override
    public List<TrainingClassDto> selectList(TrainingClassDto trainingClassDto) {
        // 1. 处理项目ID：递归查询当前项目及所有子项目的ID集合
        String frontProjectId = trainingClassDto.getProjectId();
        if (frontProjectId != null && !frontProjectId.trim().isEmpty()) {
            Set<String> projectIds = projectsService.getAllRelatedProjectIds(frontProjectId);
            trainingClassDto.setProjectIds(projectIds);
        }

        // 2. 查询班级列表
        List<TrainingClassDto> trainingClassDtos = trainingClassMapper.selectList(trainingClassDto);

        // 3. 批量处理状态字段（核心逻辑）
        for (TrainingClassDto dto : trainingClassDtos) {
            //获取培训部门名称
            R<SysDept> sysDeptR = remoteDeptService.selectDeptById(Long.parseLong(dto.getTrainingDepartment()));
            dto.setTrainingDepartmentName(sysDeptR.getData().getDeptName());
            //获取培训人数
            int trainingNum = classStudentMapper.selectStudentNumByClassId(dto.getTrainingClassId());
            dto.setTrainingNum(trainingNum);
            //获取填报人数
            int fillNum = satisfactionSurveyMapper.selectFillNumByClassId(dto.getTrainingClassId());
            dto.setFillNum(fillNum);
            // 3.1 组成人员状态（对应staffInfo）
            dto.setCompositionStatus(isFieldSet(dto.getStaffInfo()));

            // 3.2 课程状态（对应courseIds）
            dto.setCourseStatus(isFieldSet(dto.getCourseIds()));

            // 3.3 教师状态（对应teacherIds）
            dto.setTeacherStatus(isFieldSet(dto.getTeacherIds()));

            // 3.4 教材状态（对应teachingMaterialIds）
            dto.setTextbookStatus(isFieldSet(dto.getTeachingMaterialIds()));

            // 3.5 耗材状态（对应classSuppliesIds）
            dto.setConsumablesStatus(isFieldSet(dto.getClassSuppliesIds()));

            // 3.6 考试状态（对应examPaperIds）
            dto.setExamStatus(isFieldSet(dto.getExamPaperIds()));

            // 3.7 证书状态（对应certificateId）
            dto.setCertificateStatus(isFieldSet(dto.getCertificateId()));

            // 3.8 培训计划状态（对应trainingPlanDesc）
            dto.setTrainingPlanStauts(isFieldSet(dto.getTrainingPlanDesc()));

            // 3.9 费用结算状态（对应feeSettlement）
            dto.setExpenseSettlement(isFieldSet(dto.getFeeSettlement()));
        }

        return trainingClassDtos;
    }

    /**
     * 班主任查询我的班级列表
     */
    @Override
    public List<TrainingClassDto> selectMyClasses(TrainingClassDto trainingClassDto) {
        // 可以在这里添加额外的业务逻辑处理
        return trainingClassMapper.selectMyClasses(trainingClassDto);
    }

    /**
     * 获取培训班vo详细信息
     */
    @Override
    public TrainClassVo selectTrainingClassVoByTrainingClassId(String trainingClassId) {
        TrainClassVo trainClassVo = new TrainClassVo();
        TrainingClass trainingClass = trainingClassMapper.selectTrainingClassByTrainingClassId(trainingClassId);
        BeanUtils.copyProperties(trainingClass, trainClassVo);
        //获取培训项目
        if (trainClassVo.getTrainingProject() != null) {
            String trainingProject = trainClassVo.getTrainingProject();
            Projects projects = projectsService.selectProjectsByProjectId(trainingProject);
            trainClassVo.setTrainingProjectName(projects.getProjectName());
        }
        //获取培训类别
        if (trainClassVo.getTrainingType() != null) {
            String trainingType = trainClassVo.getTrainingType();
            if ("1".equals(trainingType)) {
                trainClassVo.setTrainingTypeName("新训");
            }
            if ("2".equals(trainingType)) {
                trainClassVo.setTrainingTypeName("复训");
            }
            if ("3".equals(trainingType)) {
                trainClassVo.setTrainingTypeName("补办/换证");
            }
        }
        //获取开班类型
        if (trainClassVo.getStartupType() != null) {
            String startupType = trainClassVo.getStartupType();
            if ("1".equals(startupType)) {
                trainClassVo.setStartupTypeName("线下开班");
            }
            if ("2".equals(startupType)) {
                trainClassVo.setStartupTypeName("线上开班");
            }
            if ("3".equals(startupType)) {
                trainClassVo.setStartupTypeName("混合开班");
            }
        }
        //获取班主任1
        if (trainClassVo.getHeadTeacher1() != null) {
            String headTeacher1 = trainClassVo.getHeadTeacher1();
            R<SysUser> userInfoById = remoteUserService.getUserInfoById(Long.parseLong(headTeacher1), SecurityConstants.INNER);
            trainClassVo.setHeadTeacher1Name(userInfoById.getData().getNickName());
        }
        //获取班主任2
        if (trainClassVo.getHeadTeacher2() != null) {
            String headTeacher2 = trainClassVo.getHeadTeacher2();
            R<SysUser> userInfoById = remoteUserService.getUserInfoById(Long.parseLong(headTeacher2), SecurityConstants.INNER);
            trainClassVo.setHeadTeacher2Name(userInfoById.getData().getNickName());
        }
        //获取培训部门
        if (trainClassVo.getTrainingDepartment() != null) {
            String trainingDepartment = trainClassVo.getTrainingDepartment();
            R<SysDept> sysDeptR = remoteDeptService.selectDeptById(Long.parseLong(trainingDepartment));
            trainClassVo.setTrainingDepartmentName(sysDeptR.getData().getDeptName());
        }
        //获取班级状态
        if (trainClassVo.getClassStatus() != null) {
            String classStatus = trainClassVo.getClassStatus();
            if ("1".equals(classStatus)) {
                trainClassVo.setClassStatusName("未开班");
            }
            if ("2".equals(classStatus)) {
                trainClassVo.setClassStatusName("培训中");
            }
            if ("3".equals(classStatus)) {
                trainClassVo.setClassStatusName("已结业");
            }
            if ("4".equals(classStatus)) {
                trainClassVo.setClassStatusName("已取消");
            }
        }
        return trainClassVo;
    }

    /**
     * 工具方法：判断字段是否已设置（非null且非空字符串）
     *
     * @param field 要判断的字段值
     * @return "已设置"或"未设置"
     */
    private String isFieldSet(String field) {
        // 字段不为null且不是空字符串（trim()处理空格情况）
        if (field != null && !field.trim().isEmpty()) {
            return "已设置";
        }
        return "未设置";
    }

    /**
     * 保存班级人员分配信息
     * 将接收的人员列表转换为staffInfo格式存储
     */
    @Override
    public int savePeopleAllocation(PeopleAllocationDTO allocationDTO) {
        if (allocationDTO == null || !StringUtils.hasText(allocationDTO.getTrainingClassId())
                || allocationDTO.getPeopleList() == null) {
            throw new IllegalArgumentException("参数不完整");
        }

        // 构建staffInfo字符串
        StringBuilder staffInfoBuilder = new StringBuilder();
        for (PeopleItemDTO item : allocationDTO.getPeopleList()) {
            if (item == null || !StringUtils.hasText(item.getPeopleType())) {
                continue; // 跳过无效项
            }

            // 拼接格式: peopleType:peopleId
            if (staffInfoBuilder.length() > 0) {
                staffInfoBuilder.append("/");
            }
            staffInfoBuilder.append(item.getPeopleType())
                    .append(":")
                    .append(item.getPeopleId() != null ? item.getPeopleId() : "");
        }

        // 更新培训班信息
        TrainingClass trainingClass = new TrainingClass();
        trainingClass.setTrainingClassId(allocationDTO.getTrainingClassId());
        trainingClass.setStaffInfo(staffInfoBuilder.toString());

        return trainingClassMapper.updateTrainingClass(trainingClass);
    }

    /**
     * 根据班级ID查询人员分配信息
     * 将存储的staffInfo格式转换为原始数据格式
     */
    @Override
    public PeopleAllocationDTO queryPeopleAllocation(String trainingClassId) {
        if (!StringUtils.hasText(trainingClassId)) {
            throw new IllegalArgumentException("班级ID不能为空");
        }

        // 查询班级信息
        TrainingClass trainingClass = trainingClassMapper.selectTrainingClassByTrainingClassId(trainingClassId);
        if (trainingClass == null) {
            return null;
        }

        // 构建返回对象
        PeopleAllocationDTO result = new PeopleAllocationDTO();
        result.setTrainingClassId(trainingClassId);

        // 解析staffInfo字符串
        List<PeopleItemDTO> peopleList = new ArrayList<>();
        String staffInfo = trainingClass.getStaffInfo();

        if (StringUtils.hasText(staffInfo)) {
            String[] items = staffInfo.split("/");
            for (String itemStr : items) {
                if (itemStr.contains(":")) {
                    String[] parts = itemStr.split(":", 2); // 最多分割成两部分
                    PeopleItemDTO item = new PeopleItemDTO();
                    item.setPeopleType(parts[0]);
                    item.setPeopleId(parts.length > 1 ? parts[1] : "");
                    peopleList.add(item);
                }
            }
        }

        result.setPeopleList(peopleList);
        return result;
    }

    /**
     * 班级交接
     */
    @Override
    public int classHandover(TrainingClassDto trainingClassDto) {
        //TrainingClass trainingClass = trainingClassMapper.selectTrainingClassByTrainingClassId(trainingClassDto.getTrainingClassId());
        TrainingClass trainingClass = new TrainingClass();
        trainingClass.setTrainingClassId(trainingClassDto.getTrainingClassId());
        //判断班主任2是否接收交接
        String completeHandover = trainingClassDto.getCompleteHandover();
        int result = 0;
        if ("true".equals(completeHandover)) {
            trainingClass.setHandoverStatus("2");
            result = trainingClassMapper.updateTrainingClass(trainingClass);
        }
        if ("false".equals(completeHandover)) {
            trainingClass.setHandoverStatus("0");
            result = trainingClassMapper.updateTrainingClass(trainingClass);
        }
        //保存交接备注
        if (trainingClassDto.getClassHandoverRemark() != null && !"".equals(trainingClassDto.getClassHandoverRemark())) {
            Remarks remarks = new Remarks();
            //备注信息
            remarks.setRemarks(trainingClassDto.getClassHandoverRemark());
            //备注类型
            remarks.setRemarkType(trainingClassDto.getRemarkType());
            //备注班级id
            remarks.setForeignId(trainingClassDto.getTrainingClassId());
            //备注人
            remarks.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
            //备注实践
            remarks.setCreateTime(new Date());
            return iRemarksService.insertRemarks(remarks);
        }
        return result;
    }

    /**
     * 设置培训班考试
     * lqx
     */
    @Override
    public int setExam(TrainingClass trainingClass) {
        //处理考试id,字符串拆分为数组
        if (trainingClass.getExamPaperIds() != null && !"".equals(trainingClass.getExamPaperIds())) {
            String trimmedIdStr = trainingClass.getExamPaperIds();
            List<String> currentExamIds = Arrays.stream(trimmedIdStr.split(","))//拆分,
                    .map(String::trim)// 去空格（处理每个ID的前后空格）
                    .filter(s -> !s.isEmpty())// 过滤空ID（如拆分",,1"得到的空元素）
                    .collect(Collectors.toList());  // 最终为List<String>
            //处理id生成考试安排
            //通过班级id查询该班级已关联的历史考试ID列表
            List<String> historyExamIds = examScheduleMapper.selectPaperConfigIdByClassId(trainingClass.getTrainingClassId());
            // 计算差异（需新增和需删除的考试ID）
            // 需新增：当前有但历史没有的ID
            List<String> addExamIds = currentExamIds.stream()
                    .filter(id -> !historyExamIds.contains(id))
                    .collect(Collectors.toList());
            // 需删除：历史有但当前没有的ID
            List<String> deleteExamIds = historyExamIds.stream()
                    .filter(id -> !currentExamIds.contains(id))
                    .collect(Collectors.toList());
            //批量删除（参数为List<String>）
            if (!deleteExamIds.isEmpty()) {
                //修改班级学员表中对应学员的考试安排状态("0")和考试安排id(null)
                //通过班级id和考试ids查询出对应的考试安排id
                List<String> examScheduleIds = examScheduleMapper.selectExamScheduleIdsByClassIdAndPaperConfigId(trainingClass.getTrainingClassId(),deleteExamIds);
                //修改班级学员表中对应学员的考试安排状态("0")和考试安排id(null)
                classStudentMapper.batchUpdateExamStatusByExamScheduleIdsAndClassId(trainingClass.getTrainingClassId(),examScheduleIds,"0","");
                examScheduleMapper.batchDelete(trainingClass.getTrainingClassId(), deleteExamIds);
            }
            //批量新增
            if (!addExamIds.isEmpty()) {
                List<ExamSchedule> examScheduleList = addExamIds.stream().map(examPaperId -> {
                    ExamSchedule examSchedule = new ExamSchedule();
                    //主键id
                    examSchedule.setExamScheduleId(String.valueOf(snowflake.nextId()));
                    //考试id
                    examSchedule.setPaperConfigId(examPaperId);
                    //班级id
                    examSchedule.setTrainingClassId(trainingClass.getTrainingClassId());
                    //设置创建时间
                    examSchedule.setCreateTime(new Date());
                    //设置创建人
                    examSchedule.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
//                    examSchedule.setUpdateBy("张三");
                    return examSchedule;
                }).collect(Collectors.toList());
                for (ExamSchedule examSchedule : examScheduleList) {
                    //新增考试安排
                    examScheduleMapper.insertExamSchedule(examSchedule);
                }
            }
        }
        //设置培训班考试
        return trainingClassMapper.updateTrainingClass(trainingClass);
    }

    /**
     * 通过培训班id获取培训班考试设置
     * lqx
     */
    @Override
    public List<PaperConfig> getExamInfoById(String trainingClassId) {
        TrainingClass trainingClass = trainingClassMapper.selectTrainingClassByTrainingClassId(trainingClassId);
        //处理考试id,字符串拆分为数组
        if (trainingClass.getExamPaperIds() != null && !"".equals(trainingClass.getExamPaperIds())) {
            String trimmedIdStr = trainingClass.getExamPaperIds();
            String[] examPaperIds = Arrays.stream(trimmedIdStr.split(","))//去,
                    .map(String::trim) // 去空格（处理每个ID的前后空格）
                    .filter(id -> !id.isEmpty()) // 过滤空ID（如拆分",,1"得到的空元素）
                    .toArray(String[]::new);
            List<PaperConfig> paperConfigList = new ArrayList<>();
            for (String examPaperId : examPaperIds) {
                //通过考试id去试卷信息设置表中查询信息
                PaperConfig paperConfig = trainingClassMapper.selectPaperConfigByPaperConfigId(examPaperId);
                paperConfigList.add(paperConfig);
            }
            return paperConfigList;
        }
        return null;
    }

    /**
     * 学员查询我的班级列表
     * lqx
     */
    @Override
    public List<TrainingClassDto> selectStudentClasses(String studentId) {
        //1.通过学员id查询出所在班级ids
        List<String> classIds = classStudentMapper.selectClassIdsByStudentId(studentId);
        //2.通过班级ids查询出对应的班级详细信息
        List<TrainingClassDto> trainingClassDtos = trainingClassMapper.selectListByClassIds(classIds);
        return trainingClassDtos;
    }
}
